const requesturl="43.136.220.136:5000"
Vue.use(vuePhotoPreview)
new Vue({
    el: '#xiangqingye', components: {draggable: window.vuedraggable},
    data: {
        searchQuery: '',
        onlyStarred: false,
        isRandomMode: false,
        autoPlayTimer: null,
        activeIndex: null,
        zhongjianka: null,
        uid: "",
        currentIndex: 0,
        dangqianzhuti: "",
        dangqianzhutititle: "",
        orderFromStorage: "",
        previewCards: [],
    },
    computed: {
        currentCard() {
            if (this.previewCards && this.previewCards.length > 0) {
                return this.previewCards[this.currentIndex];
            }
            return {back: '', front: '', id: null, mark: 0};
        }, filteredCards() {
            if (this.searchQuery.trim() === '') {
                return this.previewCards;
            } else {
                return this.previewCards.filter(card => card.front.toLowerCase().includes(this.searchQuery.toLowerCase()) || card.back.toLowerCase().includes(this.searchQuery.toLowerCase()));
            }
        },
    },
    methods: {
	refreshBack(){
            this.$previewRefresh();
	},
        focusSearch() {
            document.getElementById('scrollContainer').style.display = 'flex';
        },
        shijianxiandragEnd() {
            this.savePreviewCardsToLocalStorage();
        },
        toggleStarredMode() {
            this.onlyStarred = !this.onlyStarred;
        },
        toggleRandomMode() {
            this.isRandomMode = !this.isRandomMode;
        },
        stopAutoPlay() {
            if (this.autoPlayTimer) {
                clearInterval(this.autoPlayTimer);
                this.autoPlayTimer = null;
            }
        },
        zidongbofangliucheng() {
            $('#zhengmiankaneirong').trigger('click');
            setTimeout(() => this.goToNextCard(), 5000);
        },
        startAutoPlay() {
            this.stopAutoPlay();
            this.autoPlayTimer = setInterval(this.zidongbofangliucheng, 10000);
        },
        shoucangkapian() {
            this.currentCard.mark = 1;
            this.currentCard.updatetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
            console.log("🚀 ~ file: cardperform.html ~ line 370 ~ this.currentCard.updatetime: ", this.currentCard.updatetime);
            this.savePreviewCardsToLocalStorage();
        },
        quxiaoshoucangkapian() {
            this.currentCard.mark = 0;
            this.currentCard.updatetime = new Date().toISOString().slice(0, 19).replace('T', ' ');
            this.savePreviewCardsToLocalStorage();
        },
        triggerScrollToActive() {
            setTimeout(() => {
                this.scrollToActive();
            }, 500);
        },
        scrollToActive() {
            const container = document.getElementById('scrollContainer');
            const activeElements = document.querySelectorAll('.active-background');
            const activeElement = activeElements[activeElements.length - 1];
            if (activeElement) {
                const containerHeight = container.clientHeight;
                const elementTop = activeElement.offsetTop;
                const elementHeight = activeElement.clientHeight;
                const scrollTop = elementTop + elementHeight / 2 - containerHeight / 2;
                container.scrollTop = scrollTop;
            }
        },
        setActiveIndex(index) {
            this.activeIndex = index;
            this.$nextTick(() => {
                this.scrollToActive();
            });
        },
        fanhuishangyiye() {
            window.history.back()
        },
        gengxinfuwenben() {
            this.zhongjianka = this.currentCard;
            const externalEditor = this.$refs.fuwenbenbianji;
            tinymce.get(externalEditor.id).setContent(this.zhongjianka.back);
        },
        shijianxianjiantou(index) {
            this.previewCards[index].icon = "el-icon-right";
            this.previewCards[index].size = "large";
            this.previewCards[this.currentIndex].icon = '';
            this.previewCards[this.currentIndex].size = 'normal';
            this.setActiveIndex(index);
        },
        dianjishijianxian_kapian(index) {
            this.shijianxianjiantou(index);
            this.currentIndex = index;
            this.gengxinfuwenben()
        },
        existsStarredCard() {
            return this.previewCards.some(card => card.mark === 1);
        },
        goToNextCard() {
            if (this.onlyStarred && !this.existsStarredCard()) {
                alert("没有星号卡片可显示");
                return;
            }

            let nextIndex = -1;
            if (this.isRandomMode) {
                // 随机模式逻辑
                if (this.onlyStarred) {
                    const starredCards = this.previewCards.filter(card => card.mark === 1);
                    if (starredCards.length > 0) {
                        const randomIndex = Math.floor(Math.random() * starredCards.length);
                        nextIndex = this.previewCards.indexOf(starredCards[randomIndex]);
                    }
                } else {
                    nextIndex = Math.floor(Math.random() * this.previewCards.length);
                }
            } else {
                // 顺序模式逻辑
                if (this.onlyStarred) {
                    for (let i = this.currentIndex + 1; i < this.previewCards.length; i++) {
                        if (this.previewCards[i].mark === 1) {
                            nextIndex = i;
                            break;
                        }
                    }
                    if (nextIndex === -1) {
                        for (let i = 0; i <= this.currentIndex; i++) {
                            if (this.previewCards[i].mark === 1) {
                                nextIndex = i;
                                break;
                            }
                        }
                    }
                } else {
                    nextIndex = (this.currentIndex + 1) % this.previewCards.length;
                }
            }
            if (nextIndex !== -1) {
                this.dianjishijianxian_kapian(nextIndex);
                this.currentIndex = nextIndex;
                this.gengxinfuwenben();
            }
        },

        goToPreviousCard() {
            if (this.onlyStarred && !this.existsStarredCard()) {
                alert("没有星号卡片可显示");
                return;
            }

            let previousIndex = -1;
            if (this.isRandomMode) {
                // 随机模式逻辑
                if (this.onlyStarred) {
                    const starredCards = this.previewCards.filter(card => card.mark === 1);
                    if (starredCards.length > 0) {
                        const randomIndex = Math.floor(Math.random() * starredCards.length);
                        previousIndex = this.previewCards.indexOf(starredCards[randomIndex]);
                    }
                } else {
                    previousIndex = Math.floor(Math.random() * this.previewCards.length);
                }
            } else {
                // 顺序模式逻辑
                if (this.onlyStarred) {
                    for (let i = this.currentIndex - 1; i >= 0; i--) {
                        if (this.previewCards[i].mark === 1) {
                            previousIndex = i;
                            break;
                        }
                    }
                    if (previousIndex === -1) {
                        for (let i = this.previewCards.length - 1; i >= this.currentIndex; i--) {
                            if (this.previewCards[i].mark === 1) {
                                previousIndex = i;
                                break;
                            }
                        }
                    }
                } else {
                    previousIndex = this.currentIndex - 1 >= 0 ? this.currentIndex - 1 : this.previewCards.length - 1;
                }
            }

            if (previousIndex !== -1) {
                this.dianjishijianxian_kapian(previousIndex);
                this.currentIndex = previousIndex;
                this.gengxinfuwenben();
            }
        },
        toggleMark(cardId) {
            const index = this.previewCards.findIndex(item => item.id === cardId);
            if (index !== -1) {
                this.previewCards[index].mark = !this.previewCards[index].mark;
            }
            localStorage.setItem('previewCards', JSON.stringify(this.previewCards));
        },
        deleteCard(cardId) {
            this.goToPreviousCard();
            const index = this.previewCards.findIndex(card => card.id === cardId);
            if (index !== -1) {
                this.previewCards.splice(index, 1);
                this.savePreviewCardsToLocalStorage();
            }
            let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];
            shanchu.push(cardId);
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        },
        savePreviewCardsToLocalStorage() {
            if (this.previewCards.length === 0) {
                localStorage.removeItem('previewCards');
            } else {
                localStorage.setItem('previewCards', JSON.stringify(this.previewCards));
                this.saveToCenter()
            }
        },
        saveToCenter() {
            let topic = {order: '', previewCards: []};
            topic.previewCards = [...this.previewCards];
            topic.order = this.previewCards.map(card => card.id).join(',');
            this.saveToCenterZhutiXiugai();
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
            cards[this.dangqianzhuti] = topic;
            localStorage.setItem('cards', JSON.stringify(cards));
            const cards1 = JSON.parse(localStorage.getItem('cards'));
            if (cards1 && typeof cards1 === 'object') {
                let latestUpdateTime = new Date(0); // 设置初始最早的时间
                let latestCardId = null;
                Object.keys(cards1).forEach(key => {
                    let card = cards1[key];
                    //如果card下的previewCards不存在
                    if(card.previewCards!==undefined){
                    card.previewCards.forEach(previewCard => {
                        if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                        ;
                        if ('mark' in previewCard) {
                            previewCard.known = previewCard.mark;
                            delete previewCard.mark;
                        }
                        ;
                        if ('id' in previewCard) {
                            previewCard.sqlId = previewCard.id;
                            delete previewCard.id;
                        }
                        ;
                        if ('time' in previewCard) {
                            previewCard.createtime = previewCard.time;
                            delete previewCard.time;
                        }
                        ;
                        if ('updatetime' in previewCard) {
                            previewCard.lastmodifieddate = previewCard.updatetime;
                            delete previewCard.updatetime;
                            delete previewCard.icon;
                            delete previewCard.size;
                        }
                        ;previewCard.uid = this.uid;
                        previewCard.type = 1;


                        // 更新最近修改的卡片ID
                        const currentUpdateTime = new Date(previewCard.lastmodifieddate);
                        if (currentUpdateTime > latestUpdateTime) {
                            latestUpdateTime = currentUpdateTime;
                            latestCardId = previewCard.sqlId;
                        }
                    });
                    }
                });
                console.log("🚀 ~ file: cardperform.html ~ line 428 ~ latestCardId: ", latestCardId);
                this.save_xinzengids(latestCardId)
                localStorage.setItem('cards2es', JSON.stringify(cards1))
            }
        },
        saveToCenterZhutiXiugai() {
            let zhuti = localStorage.getItem('zhuti') ? JSON.parse(localStorage.getItem('zhuti')) : {};
            const dangqianzhuti = localStorage.getItem('dangqianzhuti');
            const newOrder = this.previewCards.map(card => card.id).join(',');
            if (zhuti && zhuti.topics) {
                zhuti.topics.forEach(topic => {
                    if (topic.topictitle === dangqianzhuti) {
                        topic.order = newOrder;
                        topic.edittime = new Date().toISOString().slice(0, 19).replace('T', ' ');
                    }
                });
                localStorage.setItem('zhuti', JSON.stringify(zhuti));
            }
        },
        getContentFromEditor() {
            var textarea = document.getElementById('fronttextarea');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextarea');
            var backtextarea = editor.getContent();
            const cardIndex = this.previewCards.findIndex(card => card.id === this.currentCard.id);
            if (cardIndex !== -1) {
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                this.previewCards[cardIndex].back = backtextarea;
                this.previewCards[cardIndex].front = fronttextarea;
                this.previewCards[cardIndex].updatetime = currentTime;
                this.savePreviewCardsToLocalStorage();
                alert("更新完成");
            } else alert("未找到要更新的卡片");
        },
        getContentFromEditorXinZeng() {
            var textarea = document.getElementById('fronttextareaxinzeng');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextareaxinzeng');
            var backtextarea = editor.getContent();
            const cardIndex = this.previewCards.findIndex(card => card.front === fronttextarea);
            if (cardIndex === -1) {
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                var id = this.uid + new Date().getTime().toString();
                const newCard = {
                    id: id,
                    front: fronttextarea,
                    back: backtextarea,
                    time: currentTime,
                    updatetime: currentTime,
                    mark: 0
                };
                this.previewCards.push(newCard);
                this.savePreviewCardsToLocalStorage();
                alert("新增完成");
                this.save_xinzengids(id)
            } else alert("卡片名称冲突");
        },

        save_xinzengids(id) {
            var xinzengids = localStorage.getItem('xinzengids');
            if (xinzengids) {
                xinzengids = JSON.parse(xinzengids);
                //push的时候添加去重逻辑
                if (xinzengids.indexOf(id) === -1)
                    xinzengids.push(id);
            } else xinzengids = [id];
            localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
        },

        qingkongxinzengkuang() {
            document.getElementById("fronttextareaxinzeng").value = "";
            var editor = tinymce.get('myTextareaxinzeng');
            if (editor) editor.setContent('');
        },
        sortPreviewCards() {
            return new Promise((resolve, reject) => {
                try {
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    const cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (cards[dangqianzhuti] && cards[dangqianzhuti].order) {
                        const order = cards[dangqianzhuti].order.split(',');
                        const sortedPreviewCards = [];
                        order.forEach(id => {
                            console.log("🚀 ~ file: cardperform.html ~ line 514 ~ id: ", id);
                            const foundCard = this.previewCards.find(card => card.id === id);
                            console.log("🚀 ~ file: cardperform.html ~ line 516 ~ this.previewCards: ", this.previewCards);

                            if (foundCard) sortedPreviewCards.push(foundCard);
                        });
                        this.previewCards.splice(0, this.previewCards.length, ...sortedPreviewCards);
                        console.log("🚀 ~ file: cardperform.html ~ line 519 ~ sortedPreviewCards: ", sortedPreviewCards);
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });

        },
        async fetchData() {
            try {
                const query = {query: {bool: {must: [{match: {uid: localStorage.getItem('uid')}}]}}};
                const response = await axios.post('http://'+requesturl+'/proxy-search', query);
                console.log("🚀 ~ file: cardperform.html ~ line 567 ~ response: ", response);

                const cards = {};
                response.data.hits.hits.forEach(hit => {
                    const cardData = hit._source;
                    const key = cardData.front.split('：')[0];
                    const front = cardData.front.split('：')[1];
                    if (!cards[key]) cards[key] = {order: "", previewCards: []};
                    cardData.front = front;
                    cardData.back = cardData.back;
                    cardData.mark = cardData.known;
                    delete cardData.known;
                    cardData.id = cardData.sqlId;
                    delete cardData.sqlId;
                    cardData.time = cardData.createtime;
                    delete cardData.createtime;
                    cardData.updatetime = cardData.lastmodifieddate;
                    delete cardData.lastmodifieddate;
                    delete cardData.uid;
                    delete cardData.type;
                    cards[key].previewCards.push(cardData);
                });
                //从localstorage中获取cards命名为cardsLocal,然后进行两个cards的比较，进行cards和cardsLocal的合并，合并规则：比较两个cards中的previwCards中的卡片的id是否一样，如果id一样，那么比较updatetime时间，选择时间最新的一个
                // 获取本地存储中的卡片数据
                const cardsLocal = JSON.parse(localStorage.getItem('cards')) || {};

                // 合并cards和cardsLocal
                Object.keys(cards).forEach(key => {
                    if (!cardsLocal[key]) {
                        cardsLocal[key] = cards[key];
                    } else {
                        cards[key].previewCards.forEach(card => {
                            const localCardIndex = cardsLocal[key].previewCards.findIndex(localCard => localCard.id === card.id);
                            if (localCardIndex !== -1) {
                                // 如果本地卡片存在，比较更新时间
                                if (new Date(cardsLocal[key].previewCards[localCardIndex].updatetime) < new Date(card.updatetime)) {
                                    cardsLocal[key].previewCards[localCardIndex] = card; // 使用更新时间较新的卡片，解决断网后修改的问题
                                }
                            } else {
                                // 如果本地卡片不存在，则添加
                                cardsLocal[key].previewCards.push(card);
                            }
                        });
                    }
                });

                // 更新 localStorage 中的 cards
                localStorage.setItem('cards', JSON.stringify(cardsLocal));
                console.log("Updated cards: ", cardsLocal);


                localStorage.setItem('cards', JSON.stringify(cardsLocal));
                console.log("🚀 ~ file: cardperform.html ~ line 604 ~ response: ", response);
                this.updateCardsOrderFromZhuti();

            } catch (error) {
                console.error('查询失败:', error);
            }
        },
        async fetchData1() {
            return new Promise((resolve, reject) => {
                try {
                    const query = {
                        query: {
                            bool: {
                                must: [{match: {uid: localStorage.getItem('uid')}}]
                            }
                        },
                        size: 100
                    };

                    axios.post('http://'+requesturl+'/proxy-search', query)
                        .then(async response => {
                            console.log("Response: ", response);

                            const cards = {};
                            response.data.hits.hits.forEach(hit => {
                                const cardData = hit._source;
                                const key = cardData.front.split('：')[0];
                                const front = cardData.front.split('：')[1];
                                if (!cards[key]) cards[key] = {order: "", previewCards: []};
                                cardData.front = front;
                                cardData.back = cardData.back;
                                cardData.mark = cardData.known;
                                delete cardData.known;
                                cardData.id = cardData.sqlId;
                                delete cardData.sqlId;
                                cardData.time = cardData.createtime;
                                delete cardData.createtime;
                                cardData.updatetime = cardData.lastmodifieddate;
                                delete cardData.lastmodifieddate;
                                delete cardData.uid;
                                delete cardData.type;
                                cards[key].previewCards.push(cardData);
                            });

                            const cardsLocal = JSON.parse(localStorage.getItem('cards')) || {};
                            Object.keys(cards).forEach(key => {
                                if (!cardsLocal[key]) {
                                    cardsLocal[key] = cards[key];
                                } else {
                                    cards[key].previewCards.forEach(card => {
                                        const localCardIndex = cardsLocal[key].previewCards.findIndex(localCard => localCard.id === card.id);
                                        if (localCardIndex !== -1) {
                                            if (new Date(cardsLocal[key].previewCards[localCardIndex].updatetime) < new Date(card.updatetime)) {
                                                cardsLocal[key].previewCards[localCardIndex] = card;
                                            }
                                        } else {
                                            cardsLocal[key].previewCards.push(card);
                                        }
                                    });
                                }
                            });

                            localStorage.setItem('cards', JSON.stringify(cardsLocal));
                            console.log("Updated cards: ", cardsLocal);
                            await this.updateCardsOrderFromZhuti();

                            resolve(); // 成功解决 Promise
                        })
                        .catch(error => {
                            console.error('查询失败:', error);
                            reject(error); // 在错误情况下拒绝 Promise
                        });
                } catch (error) {
                    console.error('异常错误:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
        updateCardsOrderFromZhuti() {
            return new Promise((resolve, reject) => {
                try {
                    const zhutiStorage = localStorage.getItem('zhuti');
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (zhutiStorage && dangqianzhuti) {
                        const zhuti = JSON.parse(zhutiStorage);
                        if (zhuti && zhuti.topics) {
                            zhuti.topics.forEach(topic => {
                                if (topic.topictitle === dangqianzhuti) {
                                    // 确保cards中有对应的键
                                    if (!cards[dangqianzhuti]) {
                                        cards[dangqianzhuti] = {};
                                    }
                                    cards[dangqianzhuti].order = topic.order;
                                }
                            });
                        }

                        localStorage.setItem('cards', JSON.stringify(cards));
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
        async fetchAndStoreZhuti() {
            try {
                const query = {
                    query: {
                        bool: {
                            must: [{match: {id: localStorage.getItem('uid')}}]
                        }
                    }
                };

                const response = await axios.post('http://'+requesturl+'/proxy-user-order-r', query);

                // 假设返回的内容数组中的 JSON 对象只有一个
                if (response.data.hits.hits.length > 0) {
                    const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);
                    console.log("🚀 ~ file: cardperform.html ~ line 741 ~ zhutiData: ", zhutiData);
                    //todo 取出zhutiData中的所有edittime最大的一个，跟当前localstorage中的zhuti中的所有的edittime中最大的一个进行对比，如果localstorage中的zhuti中的最大的edittime大于等于当前的最大的edittime，那么就不进行替换，否则进行替换。
                    // 获取zhutiData中最大的edittime
                    console.log("🚀 ~ file: cardperform.html ~ line 783 ~ zhutiData.topics: ", zhutiData);
                    const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                    console.log("🚀 ~ file: cardperform.html ~ line 783 ~ maxEditTimeZhutiData: ", maxEditTimeZhutiData);

                    // 获取localStorage中zhuti的最大edittime
                    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                    const maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                        ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                        : 0;
                    console.log("🚀 ~ file: cardperform.html ~ line 788 ~ maxEditTimeLocalZhuti: ", maxEditTimeLocalZhuti);
                    // 对比edittime，如果需要则更新localStorage中的zhuti
                    if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                        localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                    }
                } else {
                    console.log('未找到匹配的数据');
                }
            } catch (error) {
                console.error('查询失败:', error);
                alert("检查网络是否连接失败")
            }
        },
        fetchAndStoreZhuti1() {
            return new Promise((resolve, reject) => {
                const query = {
                    query: {
                        bool: {
                            must: [{match: {id: localStorage.getItem('uid')}}]
                        }
                    }, size: 100
                };

                axios.post('http://'+requesturl+'/proxy-user-order-r', query)
                    .then(async response => {
                        let maxEditTimeLocalZhuti = 0;
                        if (response.data.hits.hits.length > 0) {
                            const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);
                            console.log("zhutiData: ", zhutiData);

                            const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                            const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                            maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                                ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                                : 0;

                            if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                                localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                            }
                            await this.updateCardsOrderFromZhuti()
                            //将maxEditTimeZhutiData保存到localStorage中，以便下次比较
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeZhutiData);
                            resolve(); // 成功解决Promise
                        } else {
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
                            console.log('未找到匹配的数据');
                            resolve(); // 未找到数据也视为解决Promise
                        }
                    })
                    .catch(error => {
                        console.error('查询失败:', error);
                        reject(error); // 发生错误时拒绝Promise
                    });


            });
        },
        pageInit() {
            return new Promise((resolve, reject) => {
                console.log("🚀 ~ file: cardperform.html ~ line 739 ~ pageInit: ");
                this.dangqianzhuti = localStorage.getItem('dangqianzhuti');
                this.dangqianzhutititle = localStorage.getItem('dangqianzhutititle');
                console.log("🚀 ~ file: cardperform.html ~ line 741 ~ dangqianzhuti: ", this.dangqianzhuti);
                let previewCardsFromStorage = [];
                let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                if (cards[this.dangqianzhuti] && cards[this.dangqianzhuti].previewCards) {

                    previewCardsFromStorage = cards[this.dangqianzhuti].previewCards;
                    this.orderFromStorage = cards[this.dangqianzhuti].order;
                }
                ;
                if (previewCardsFromStorage.length > 0) {
                    localStorage.setItem('previewCards', JSON.stringify(previewCardsFromStorage));
                } else {
                    localStorage.setItem('previewCards', JSON.stringify([]));
                }
                ;const storedCards = localStorage.getItem('previewCards');
                console.log("🚀 ~ file: cardperform.html ~ line 757 ~ storedCards: ", storedCards);
                if (storedCards) {
                    try {
                        this.previewCards = JSON.parse(storedCards);
                        console.log("🚀 ~ file: cardperform.html ~ line 761 ~ JSON.parse(storedCards): ", JSON.parse(storedCards));
                        this.zhongjianka = this.currentCard;
                        // this.sortPreviewCards();
                        resolve(); // 解决 Promise
                    } catch (error) {
                        console.error('Error:', error);
                        reject(error); // 如果有错误，拒绝 Promise
                    }
                } else {
                    resolve(); // 如果没有存储的卡片，也解决 Promise
                }
            });

        }

    },
    mounted() {
        var self = this
        const uid = localStorage.getItem('uid');
        if (uid) {
            this.uid = uid
        } else {
            alert("请登录")
        }
        //
        this.fetchData1().then(() => {
            this.fetchAndStoreZhuti1().then(() => {
                this.pageInit().then(() => {
                    this.sortPreviewCards().then(() =>
                    {
                        const previewCards = JSON.parse(localStorage.getItem('previewCards') || '[]');
                        if (previewCards.length > 0) {
                            document.getElementById('jiazaizhongdonghua').style.display = 'none';
                            localStorage.setItem('initTinyMCE', 'false');
                        }else{
                            localStorage.setItem('initTinyMCE', 'true');
                        }
                    })
                    localStorage.setItem('dangqianzhutititle','00000000000')
                })
            })
        })

        this.pageInit()
    }
});


async function push2es() {
    let xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    if (!xinzengids.length) return;
    // 复制待新增的ID列表
    const idsToAdd = [...xinzengids];
    console.log("待批量新增的卡片IDs: ", idsToAdd);
    const cards2es = JSON.parse(localStorage.getItem('cards2es'));
    console.log("🚀 ~ file: cardperform.html ~ line 442 ~ cards2es: ", cards2es);
    let bulkBody = '';
    const now = new Date().getTime();

    Object.keys(cards2es).forEach(key => {
        console.log("🚀 ~ file: cardperform.html ~ line 447 ~ key: ", cards2es[key].previewCards);
        if(cards2es[key].previewCards!=undefined){
        cards2es[key].previewCards.forEach(card => {
            console.log("🚀 ~ file: cardperform.html ~ line 449 ~ card: ", card);
            // 从ids字符数组中拿到待新增的数组内容，
            if (idsToAdd.includes(card.sqlId)) {
                bulkBody += JSON.stringify({index: {_index: 'users', _type: '_doc', _id: card.sqlId}}) + '\n';
                bulkBody += JSON.stringify(card) + '\n';
            }
        });}
    });

    if (bulkBody) {
        console.log("🚀 ~ file: cardperform.html ~ line 459 ~ bulkBody: ", bulkBody);
        axios.post('http://'+requesturl+'/proxy-bulk', bulkBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
                console.log('Bulk operation successfully executed', response.data);
                // 从xinzengids数组中移除已新增的IDs
                xinzengids = xinzengids.filter(id => !idsToAdd.includes(id));
                localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
            }
        ).catch(error => console.error('Failed to execute bulk operation', error));
    }
}

// 定时任务
setInterval(push2es, 1000 * 20 ); // 每3分钟执行一次


// 修改后的deleteEsIds方法
async function deleteEsIds() {
    let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];
    if (!shanchu.length) return;

    // 复制待删除的ID列表
    const idsToDelete = [...shanchu];
    console.log("🚀 ~ file: cardperform.html ~ line 594 ~ idsToDelete: ", idsToDelete);
    //从localstorage中获取xinzengids
    const xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    let bulkDeleteBody = '';
    idsToDelete.forEach(id => {
        //如果xinzengids中包含这个id则不执行删除这个id
        if (xinzengids.includes(id)) {
            console.log('Skipping deletion of ID ' + id + ' because it is in the xinzengids list.');
            return;
        }
        bulkDeleteBody += JSON.stringify({delete: {_index: 'users', _type: '_doc', _id: id}}) + '\n';
    });


    if (bulkDeleteBody) {
        axios.post('http://'+requesturl+'/proxy-bulk', bulkDeleteBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
            console.log('Bulk delete operation successfully executed', response.data);
            // 从shanchu数组中移除已删除的IDs
            shanchu = shanchu.filter(id => !idsToDelete.includes(id));
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        }).catch(error => console.error('Failed to execute bulk delete operation', error));
    }
}

// 设置定时任务，定期调用deleteEsIds
setInterval(deleteEsIds, 60 * 1000 * 2); // 比如每两分钟执行一次


function saveZhutiToElasticsearch() {
    const zhuti = localStorage.getItem('zhuti');
    const uid = localStorage.getItem('uid');

    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
    var maxEditTimeLocalZhuti = localZhuti.topics.length > 0
        ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
        : 0;
    //获取maxEditTimeZhuti并和maxEditTimeLocalZhuti进行比较，如果maxEditTimeZhuti大于maxEditTimeLocalZhuti，则说明有新的数据需要同步到Elasticsearch
    const maxEditTimeZhuti = localStorage.getItem('maxEditTimeZhuti') || 0;
    if (maxEditTimeZhuti < maxEditTimeLocalZhuti) {

        if (zhuti && uid) {
            const data = {
                id: uid,
                zhuti: zhuti
            };

            axios.post('http://'+requesturl+'/proxy-user-order-cud', data).then(response => {
                console.log('Data successfully saved to Elasticsearch', response.data);
                //更新maxEditTimeZhuti
                localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
            }).catch(error => {
                console.error('Failed to save data to Elasticsearch', error);
            });

        }
    } else {
        console.log("no new zhuti data to save")
    }
}

// 设置定时任务，每5分钟执行一次
setInterval(saveZhutiToElasticsearch, 20000);
// 你可以使用beforeunload事件来监控页面退出的动作,成功了，关闭的时候执行发送了。
window.addEventListener('beforeunload', function (event) {
    // 在这里编写你的函数代码
    push2es()
    deleteEsIds()
    saveZhutiToElasticsearch()
});

function updateOnlineStatus() {
    if (!navigator.onLine) {
        // 当用户处于离线状态时
        alert("网络异常，请检查您的网络连接！");
    }
}

// 监听网络状态变化事件
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

// 初始检查
updateOnlineStatus();


    function tinymcechushihuamyTextarea(idString,sfjixu) {
    var globalFunctionRequestReplaceExpressProxy="http://baota.memlee.top:4000"
    var imageCompression = function(base64, w){
    return new Promise(function(resolve, reject) {
    console.log("enter promise")
    var newImage = new Image();
    var quality = 0.6;
    console.log("压缩前",imgPasteUrl.length/1024)
    newImage.src = imgPasteUrl;
    newImage.setAttribute("crossOrigin", 'Anonymous');
    var imgWidth, imgHeight;
    newImage.onload = function () {
    imgWidth = this.width; imgHeight = this.height;
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    if (Math.max(imgWidth, imgHeight) > w)
{if (imgWidth > imgHeight)
{canvas.width = w; canvas.height = w * imgHeight / imgWidth;}
    else
{canvas.height = w; canvas.width = w * imgWidth / imgHeight;}
}
    else
{canvas.width = imgWidth; canvas.height = imgHeight; quality = 0.6;}
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
    var base64 = canvas.toDataURL("image/jpeg", quality);
    if (base64.length / 1024 > 1024) {
    quality = (1024-200)/(base64.length / 1024)
    base64 = canvas.toDataURL("image/jpeg", quality);
}
    if (base64.length / 1024 < 50) {
    quality = 50+20/(base64.length /1024 )
    base64 = canvas.toDataURL("image/jpeg", quality);
}
    resolve(base64);
}
})
}
    var imgPasteUrl = ""   //全局变量用于存储上传图片路径
    function uploadImg2Gitee(img, success, failure) {
    var base64 = img.split(",")[1]
    var timestamp = new Date().getTime()
    var imgname = timestamp + '.jpg'
    $.ajax({
    url: "https://gitee.com/api/v5/repos/li521miao/images/contents/" + imgname,
    type: "post",
    data: '{"access_token":"199bec3847cb284ca03f139970f7b691","content":"' + base64 + '","message":"upload for images"}',
    dataType: 'json',
    processData: false,
    async: false,
    contentType: "application/json;charset=UTF-8",
    success: function (data) {
    console.log(globalFunctionRequestReplaceExpressProxy)
    var imgSrc = data.content.download_url.replace("https://gitee.com",globalFunctionRequestReplaceExpressProxy)
    success(imgSrc)
},
    error: function (e) {
    alert("error");
    console.log(e)
    failure(e)
}
})
}
    var ifInline = false;
    if(sfjixu==3){
     ifInline=true
    }
    // 在这里编写函数的代码
    tinymce.init({
    selector: idString, // 指定要初始化的<textarea>元素的ID
    inline: ifInline,
    mobile: {
    menubar: true
},
    language_url: 'http://43.136.220.136/static/tinymce-lang-zh@5.2.2.js', // 指定语言文件的URL https://cdn.jsdelivr.net/gh/wt-sml/wutong_cdn/js/tinymce-lang-zh@5.2.2.js
    language: 'zh_CN', // 设置语言为中文
    skin_url: 'http://43.136.220.136/static/skin.min.css', // 指定皮肤文件的URL
    height: 400, // 设置编辑器高度
    plugins: [
    "advlist autolink lists link image axupimgs charmap preview hr anchor",
    "searchreplace wordcount visualblocks visualchars code fullscreen",
    "insertdatetime nonbreaking save table contextmenu directionality",
    "emoticons paste textcolor colorpicker textpattern code lineheight"
    ],
    content_style: 'img {  max-width: 100%;  height: auto; }',
    textpattern_patterns: [
{start: '*', end: '*', format: 'italic'},
{start: '**', end: '**', format: 'bold'},
{start: '#', format: 'h1'},
{start: '##', format: 'h2'},
{start: '###', format: 'h3'},
{start: '####', format: 'h4'},
{start: '#####', format: 'h5'},
{start: '######', format: 'h6'},
{start: '1. ', cmd: 'InsertOrderedList'},
{start: '* ', cmd: 'InsertUnorderedList'},
{start: '- ', cmd: 'InsertUnorderedList'},
{start: '//brb', replacement: 'Be Right Back'}
    ],
    toolbar:
    'image axupimgs  | undo redo | bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | link unlink code | removeformat',
    branding: false,
    menubar: true,
    images_upload_handler: async (blobInfo, success, failure) => {
    var img = ""
    if (blobInfo.base64 != undefined) {
    img = 'data:image/jpeg;base64,' + blobInfo.base64()
} else {
    var asyncReader = function(){
    return new Promise(function(resolve,reject){
    const reader = new FileReader();
    reader.addEventListener('load', async () => {
    img = reader.result + ''
    //在这里使用压缩算法
    imgPasteUrl = img
    img = await imageCompression(img, 1400)
    console.log("压缩后", img.length / 1024);
    resolve(img)
});
    reader.readAsDataURL(blobInfo.blob());
})
}
    img =  await asyncReader()
}
    if (img != "") {
    imgPasteUrl = img
    img = await imageCompression(img, 1400)
    console.log("压缩后", img.length / 1024);
    console.log("center")
    console.log("end")
}
    uploadImg2Gitee(img, success, failure);
},
    paste_data_images: true,
    paste_preprocess: async function (plugin, args) {
},
    images_upload_credentials: true,
    images_reuse_filename: true,
    image_advtab: true,
    images_upload_base_path: '',
    images_upload_url: 'doFileUpload.asp',
    automatic_uploads: true,
    file_picker_types: 'file, image, media',
    file_picker_callback: function (callback, value, meta) {
},
    images_dataimg_filter: function (img) {
    //可以在这里把文件上传，使用全局参数保存路径，最后在处理的时候替换img.src实现
    imgPasteUrl = img
    return !img.hasAttribute('internal-blob');  // blocks the upload of <img> elements with the attribute "internal-blob".
},
    init_instance_callback: function (editor) {
    if(sfjixu===1){
    tinymcechushihuamyTextarea("#myTextareaxinzeng",0)
    const initTinyMCE = localStorage.getItem('initTinyMCE') === 'true';
    if (initTinyMCE) {
        document.getElementById('jiazaizhongdonghua').style.display = 'none';
        // 完成后，重置标志以避免影响后续逻辑
        localStorage.setItem('initTinyMCE', 'false');
    }
    // document.getElementById('jiazaizhongdonghua').style.display = 'none';
    console.log('TinyMCE 初始化完成');
}
}
});
}
    window.onload = function() {// myTextareaxinzeng
    tinymcechushihuamyTextarea("#myTextarea", 1)
}
document.addEventListener('DOMContentLoaded', (event) => {
    var myDiv = document.getElementById('bianjimoshi');
    myDiv.addEventListener('click', function() {
        alert('div被点击了！');
        tinymcechushihuamyTextarea('#beimianbianji',3) 
    });
})


